<?php
use Workerman\Worker;
use Consumer\Tool;
use Workerman\Lib\Timer;

require_once __DIR__ . '/vendor/workerman/workerman/Autoloader.php';
require_once __DIR__ . '/vendor/workerman/channel/src/Server.php';
require_once __DIR__ . '/vendor/workerman/channel/src/Client.php';

include __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/config.php';


// 初始化一个Channel服务端
$channel_server = new Channel\Server('0.0.0.0', 2206);

// websocket服务端
$worker = new Worker('websocket://0.0.0.0:2120');
$worker->count=8;
$worker->name = 'pusher';
$worker->onWorkerStart = function($worker)
{
	// Channel客户端连接到Channel服务端
    Channel\Client::connect('127.0.0.1', 2206);
    // 以自己的进程id为事件名称
    $event_name = $worker->id;
    // 订阅worker->id事件并注册事件处理函数
    Channel\Client::on($event_name, function($event_data)use($worker){
        $to_connection_id = $event_data['to_connection_id'];
        $message = $event_data['content'];
        if(!isset($worker->connections[$to_connection_id]))
        {
            echo "connection not exists\n";
            return;
        }
        $to_connection = $worker->connections[$to_connection_id];
        $to_connection->send($message);
    });

};

$worker->onConnect = function($connection)use($worker)
{
    $msg = "workerID:{$worker->id} connectionID:{$connection->id} connected\n";
    $connection->send($msg);
};

$redis = Tool::getRedisModule();
$worker->onMessage = function($connection,$uid)use($worker)
{
	$redis = Tool::getRedisModule();
    $uid = (string) $uid;
    $key = ON_LINE_USER_ID . $uid;
	$redis->multi();
	$redis->rpush(ON_LINE_USER_ID_LIST, $uid);
	$redis->set($key, $uid);
	$redis->set(USER_ON_LINE_CONN.$uid,$worker->id.'_'.$connection->id);
	$redis->exec();
	$connection->uid = $uid;
};
$worker->onClose = function($connection)
{
	global $redis;
	$redis->multi();
    $redis->lrem(ON_LINE_USER_ID_LIST, $connection->uid);
    $redis->remove(ON_LINE_USER_ID . $connection->uid);
	$redis->remove(USER_ON_LINE_CONN.$connection->uid);
	$redis->exec();
};

if (!defined('GLOBAL_START')) {
    Worker::runAll();
}